/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.ctu.guiproject.server.manager;

import cz.ctu.guiproject.server.resources.Constants;
import cz.ctu.guiproject.server.resources.FileLoader;
import guiproject.server.view.View;
import java.io.IOException;
import java.io.StringReader;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author tomas.buk
 */
public class LayoutManagerImpl implements LayoutManager {

    private static final Logger logger = Logger.getLogger(LayoutManagerImpl.class.getName());
    
    private static LayoutManager instance;
    private static final JARManager jarManager;
    static {
        jarManager = JARManager.getInstance();
    }

    private LayoutManagerImpl() {
        init();
    }

    public static LayoutManager getInstance() {
        if (instance == null) {
            instance = new LayoutManagerImpl();
        }
        return instance;
    }

    private void init() {
        // TODO specify which file to load!
        final String layout = FileLoader.loadTextFile(Constants.LAYOUT_XML_PATH);
        decodeInitialServerSideLayout(layout);
    }

    private void decodeInitialServerSideLayout(String xml) {
        final SAXParserFactory factory = SAXParserFactory.newInstance();
        final DefaultHandler handler = new InitialServerSideLayoutHandler();
        try {
                final SAXParser saxParser = factory.newSAXParser();
                saxParser.parse(new InputSource(new StringReader(xml)), handler);
        } catch (ParserConfigurationException | SAXException | IOException e) {
                logger.severe(e.getMessage());
        }
    }
    
    private class InitialServerSideLayoutHandler extends DefaultHandler {
        
        // TODO mozny vznik problemu, pokazde volana nova instance!
        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            // send to JARManager, whether entity of that name exists
            final View view = jarManager.getView(qName, attributes);
            if(view == null) {
                logger.severe("Corresponding view " + qName + " not found!");
            }
        }
    }
    
    @Override
    public View getView(String viewId) {
        return jarManager.getView(viewId);
    }
}